<template>
	<view class="sequence">
		<zero-custom-bar :singleIcon="true" backgroundColor="#3073f6" title="顺序练习" color="#fff" :singleIconType="'back'">
		</zero-custom-bar>
		
		<!-- 用户信息和考试目标卡片 -->
		<view class="user-goal-card">
			<view class="user-section">
				<view class="user-avatar">
					<image :src="userInfo.avatar || '/static/img/userinfo.png'" mode="aspectFill"></image>
				</view>
				<view class="user-details">
					<text class="user-name">{{ userInfo.nickname || '未设置姓名' }}</text>
					<view class="user-info-row">
						<text class="info-label">身份证：</text>
						<text class="info-value">{{ maskIdentity(userInfo.identity) || '未设置' }}</text>
					</view>
					<view class="user-info-row">
						<text class="info-label">手机号：</text>
						<text v-if="userInfo.phone" class="info-value">{{ maskPhone(userInfo.phone) || '未设置' }}</text>
						<view class="modify-btn-wrapper" @click="showModifyPhonePopup">
              <text class="modify-btn-text">{{ userInfo.phone ? '号码不对？' : '请先绑定手机号' }}</text>
							<text class="modify-btn">{{ userInfo.phone ? '修改' : '绑定' }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 练习统计卡片 -->
		<view class="stats-card">
			<view class="stats-header">
				<text class="stats-title">练习统计</text>
			</view>
			<view class="stats-grid">
				<view class="stats-item">
					<text class="stats-number">{{ data.sumRight || 0 }}</text>
					<text class="stats-label">正确题</text>
				</view>
				<view class="stats-item">
					<text class="stats-number">{{ data.madeTotal || 0 }}</text>
					<text class="stats-label">已做题</text>
				</view>
				<view class="stats-item">
					<text class="stats-number error">{{ data.sumError || 0 }}</text>
					<text class="stats-label">错题</text>
				</view>
				<view class="stats-item">
					<text class="stats-number" :class="{ 'low-rate': rate < 80 }">
						{{ Number(data.sumRight) ? Math.round(Number(data.sumRight)/(Number(data.sumError)+Number(data.sumRight))*100) : 0 }}%
					</text>
					<text class="stats-label">正确率</text>
				</view>
			</view>
		</view>

		<!-- 开始练习按钮 -->
		<view class="practice-card">
			<view class="practice-header">
				<text class="practice-title">{{ opcname }}</text>
			</view>
			<navigator class="practice-btn" :render-link="false" :url="`/pages/question/questionList?opc=${opc}&type=${type}&opcname=${opcname}`">
				<view class="practice-content">
					<view class="practice-info">
						<text class="practice-name">顺序练习</text>
						<text class="practice-desc">题库共有{{ data.total }}道题</text>
					</view>
					<view class="practice-action">
						<text class="action-text">继续答题</text>
						<text class="iconfont icon-arrow-right"></text>
					</view>
				</view>
			</navigator>
		</view>
		
		<!-- 修改手机号弹窗 -->
		<view v-if="showModifyPhone" class="modify-phone-modal" @tap="hideModifyPhonePopup">
			<view class="modify-phone-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">修改手机号</text>
					<text class="close-btn" @tap="hideModifyPhonePopup">×</text>
				</view>
				
				<view class="modal-body">
					<view class="step">
						<text class="step-title">修改手机号</text>
						<view class="input-group">
							<text class="input-label">当前手机号</text>
							<input type="text" class="phone-input" :value="userInfo.phone" disabled />
						</view>
						<view class="input-group">
							<text class="input-label">新手机号</text>
							<input type="number" class="phone-input" placeholder="请输入新手机号" v-model="newPhone" maxlength="11" />
						</view>
						<view class="input-group">
							<text class="input-label">验证码</text>
							<view class="code-input-wrapper">
								<input type="number" class="code-input" placeholder="请输入验证码" v-model="newPhoneCode" maxlength="6" />
								<text class="send-code-btn" @tap="sendNewPhoneCode" :class="{ disabled: newCodeCountdown > 0 || !newPhone }">
									{{ newCodeCountdown > 0 ? `${newCodeCountdown}s` : '发送验证码' }}
								</text>
							</view>
						</view>
						<button class="confirm-btn" @tap="confirmModifyPhone" :disabled="!newPhone || !newPhoneCode">确认修改</button>
					</view>
				</view>
			</view>
		</view>
    <login-popup @success="registerSuccess" :slogan="slogan" :title="title"
				:tokenNoPhone="token" ref="applogin"></login-popup>
	</view>
</template>

<script>
import { getTrainTotal } from '@/http/question'
import { getPhoneCode, putChangePhone, authCodePhone, putUserUpdate, getDetail } from '@/http/user'
import { maskPhone, maskIdentity } from '@/utils/tools'
import loginPopup from '@/components/login-popup/loginPopup.vue'

export default {
  components: {
    loginPopup
  },
  data() {
    return {
      rate: 0,
      opc: '',
      type: '',
      opcname: '',
      data: {},
      userInfo: {},
      // 修改手机号相关
      showModifyPhone: false,
      newPhone: '',
      newPhoneCode: '',
      newCodeCountdown: 0,
      newCodeTimer: null,
      token:'',
      slogan:'',
      title:''
    }
  },
  onLoad(options) {
    this.opc = options.opc
    this.type = options.type
    this.opcname = options.opcname
    uni.setNavigationBarTitle({
      title: options.opcname
    })
  },
  onShow() {
    this.getUserInfo()
    this.getRate()
  },
  onUnload() {
    // 清理定时器
    if (this.newCodeTimer) {
      clearInterval(this.newCodeTimer)
      this.newCodeTimer = null
    }
  },
  methods: {
    maskPhone,
    maskIdentity,
    getUserInfo() {
      const userInfo = uni.getStorageSync('userinfo')
      if (userInfo) {
        this.userInfo = {
          ...userInfo,
          phone: userInfo.phone || '',
          identity: userInfo.identity || '',
          nickname: userInfo.nickname || '',
          avatar: userInfo.avatar || '/static/img/userinfo.png'
        }
      }
    },
    // 显示修改手机号弹窗
    showModifyPhonePopup() {
      // if (!this.userInfo.phone) {
      //   uni.showToast({
      //     title: '请先绑定手机号',
      //     icon: 'none'
      //   })
      //   return
      // }
      this.title = '完善信息'
      this.slogan = '-完善信息以获得完整功能-'
      this.token = uni.getStorageSync('token')
      console.log(this.userInfo, 'this.userInfo188');
      
      this.$refs.applogin.show(this.userInfo)
    },
    registerSuccess(){
			this.$refs.applogin.close()
      getDetail().then(res => {
        uni.setStorageSync('userinfo', res.data)
        this.getUserInfo()
      })
    },
    // 隐藏修改手机号弹窗
    hideModifyPhonePopup() {
      this.showModifyPhone = false
      this.resetModifyData()
    },
    // 重置修改数据
    resetModifyData() {
      this.oldPhoneCode = ''
      this.newPhone = ''
      this.newPhoneCode = ''
      this.oldCodeCountdown = 0
      this.newCodeCountdown = 0
      if (this.oldCodeTimer) {
        clearInterval(this.oldCodeTimer)
        this.oldCodeTimer = null
      }
      if (this.newCodeTimer) {
        clearInterval(this.newCodeTimer)
        this.newCodeTimer = null
      }
    },
    // 发送当前手机号验证码
    async sendOldPhoneCode() {
      if (this.oldCodeCountdown > 0) return
      
      try {
        uni.showLoading({ title: '发送中...' })
        await getPhoneCode({ phone: this.userInfo.phone })
        uni.hideLoading()
        
        this.oldCodeCountdown = 60
        this.oldCodeTimer = setInterval(() => {
          this.oldCodeCountdown--
          if (this.oldCodeCountdown <= 0) {
            clearInterval(this.oldCodeTimer)
            this.oldCodeTimer = null
          }
        }, 1000)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: error.data.message || '发送失败',
          icon: 'none'
        })
      }
    },
    // 验证当前手机号
    async verifyOldPhone() {
      if (!this.oldPhoneCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '验证中...' })
        await authCodePhone({
          phone: this.userInfo.phone,
          authCode: this.oldPhoneCode
        })
        uni.hideLoading()
        
        this.modifyStep = 2
        uni.showToast({
          title: '验证成功',
          icon: 'success'
        })
      } catch (error) {
        console.log(error);
        uni.showToast({
          title: error.data.message || '验证码错误',
          icon: 'none'
        })
      }
    },
    // 发送新手机号验证码
    async sendNewPhoneCode() {
      if (this.newCodeCountdown > 0 || !this.newPhone) return
      
      if (!/^1\d{10}$/.test(this.newPhone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      
      if (this.newPhone === this.userInfo.phone) {
        uni.showToast({
          title: '新手机号不能与当前手机号相同',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({ title: '发送中...' })
        await getPhoneCode({ phone: this.newPhone })
        uni.hideLoading()
        
        this.newCodeCountdown = 60
        this.newCodeTimer = setInterval(() => {
          this.newCodeCountdown--
          if (this.newCodeCountdown <= 0) {
            clearInterval(this.newCodeTimer)
            this.newCodeTimer = null
          }
        }, 1000)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      }
    },
    // 确认修改手机号
    async confirmModifyPhone() {
      if (!this.newPhone || !this.newPhoneCode) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }
   
      try {
        uni.showLoading({ title: '修改中...' })
        await authCodePhone({
          phone: this.newPhone,
          authCode: this.newPhoneCode
        })
        uni.hideLoading()
        
        // 更新本地用户信息
        const userInfo = uni.getStorageSync('userinfo')
        if (userInfo) {
          userInfo.phone = this.newPhone
          putUserUpdate({
            phone: this.newPhone
          }).then(res => {
           uni.setStorageSync('userinfo', userInfo)
            this.getUserInfo()
          })
         
        }
        
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
        
        this.hideModifyPhonePopup()
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: error.data.message || '修改失败',
          icon: 'none'
        })
      }
    },
    getRate() {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
      getTrainTotal({opc: this.opc}).then(res => {
        uni.hideLoading()
        this.data = res.data
        console.log(res.data)
      }).catch(err => {
        uni.hideLoading()
        console.log(err);
        if(err.data.code == 401){
          uni.showToast({
            title: '登录过期，请重新登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.sequence {
  min-height: 100vh;
  background: linear-gradient(180deg, #3073f6, #3073f6, #ffffff);
  background-size: 100% 535rpx;
  background-repeat: no-repeat;
  padding-bottom: 40rpx;
}

/* 用户信息和考试目标合并卡片 */
.user-goal-card {
  margin: 30rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  
  .user-section {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    
    .user-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50rpx;
      overflow: hidden;
      margin-right: 24rpx;
      border: 4rpx solid rgba(255, 255, 255, 0.8);
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    .user-details {
      flex: 1;
      
      .user-name {
        font-size: 36rpx;
        font-weight: 700;
        color: #333;
        margin-bottom: 16rpx;
        display: block;
      }
      
      .user-info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
        
        .info-label {
          font-size: 26rpx;
          color: #666;
          min-width: 120rpx;
        }
        
        .info-value {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
          flex: 1;
        }
        .modify-btn-wrapper{
          display: flex;
          align-items: center;
        }
        .modify-btn-text{
          font-size: 24rpx;
        }
        .modify-btn {
          font-size: 24rpx;
          color: #3073f6;
          background: rgba(48, 115, 246, 0.1);
          padding: 5rpx 8rpx;
          border-radius: 12rpx;
          &:active {
            background: rgba(48, 115, 246, 0.2);
          }
        }
      }
    }
  }
  
  .divider {
    height: 2rpx;
    background: linear-gradient(90deg, transparent, rgba(48, 115, 246, 0.2), transparent);
    margin: 24rpx 0;
  }
  
  .goal-section {
    .goal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;
      
      .goal-title {
        font-size: 32rpx;
        font-weight: 700;
        color: #333;
      }
      
      .goal-icon {
        width: 60rpx;
        height: 60rpx;
        background: linear-gradient(135deg, #3073f6, #4a90e2);
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .iconfont {
          font-size: 32rpx;
          color: #fff;
        }
      }
    }
    
    .goal-content {
      margin-bottom: 24rpx;
      
      .goal-main {
        font-size: 40rpx;
        font-weight: 700;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .goal-sub {
        font-size: 28rpx;
        color: #ff6b6b;
        font-weight: 600;
      }
    }
    
    .goal-tips {
      display: flex;
      align-items: center;
      background: linear-gradient(135deg, rgba(48, 115, 246, 0.1), rgba(74, 144, 226, 0.1));
      border-radius: 16rpx;
      padding: 20rpx;
      
      .tips-icon {
        margin-right: 16rpx;
        
        .iconfont {
          font-size: 32rpx;
          color: #3073f6;
        }
      }
      
      .tips-text {
        flex: 1;
        font-size: 26rpx;
        color: #666;
        line-height: 1.5;
      }
      
      .tips-arrow {
        .iconfont {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}



/* 练习统计卡片 */
.stats-card {
  margin: 30rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  
  .stats-header {
    margin-bottom: 32rpx;
    
    .stats-title {
      font-size: 32rpx;
      font-weight: 700;
      color: #333;
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    gap: 16rpx;
    
    .stats-item {
      text-align: center;
      padding: 16rpx 8rpx;
      background: linear-gradient(135deg, rgba(48, 115, 246, 0.05), rgba(74, 144, 226, 0.05));
      border-radius: 12rpx;
      border: 2rpx solid rgba(48, 115, 246, 0.1);
      
      .stats-number {
        font-size: 36rpx;
        font-weight: 700;
        color: #333;
        display: block;
        margin-bottom: 4rpx;
        
        &.error {
          color: #ff6b6b;
        }
        
        &.low-rate {
          color: #ff6b6b;
        }
      }
      
      .stats-label {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}

/* 开始练习卡片 */
.practice-card {
  margin: 30rpx;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  overflow: hidden;
  
  .practice-header {
    padding: 24rpx 32rpx;
    border-bottom: 2rpx solid rgba(255, 107, 107, 0.1);
    
    .practice-title {
      font-size: 32rpx;
      font-weight: 700;
      color: #333;
    }
  }
  
  .practice-btn {
    display: block;
    
    &:active .practice-content {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.4);
    }
    
    .practice-content {
      padding: 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: linear-gradient(135deg, #3073f6, #4a90e2);
      box-shadow: 0 4rpx 16rpx rgba(107, 213, 255, 0.3);
      transition: all 0.3s ease;
      
      .practice-info {
        .practice-name {
          font-size: 36rpx;
          font-weight: 700;
          color: #fff;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .practice-desc {
          font-size: 26rpx;
          color: rgba(255, 255, 255, 0.8);
        }
      }
      
      .practice-action {
        display: flex;
        align-items: center;
        
        .action-text {
          font-size: 28rpx;
          color: #fff;
          font-weight: 600;
          margin-right: 8rpx;
        }
        
        .iconfont {
          font-size: 24rpx;
          color: #fff;
        }
      }
    }
  }
}

/* 修改手机号弹窗样式 */
.modify-phone-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modify-phone-content {
    width: 600rpx;
    background: #fff;
    border-radius: 24rpx;
    overflow: hidden;
    max-height: 80vh;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 2rpx solid #f0f0f0;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: 700;
        color: #333;
      }
      
      .close-btn {
        font-size: 48rpx;
        color: #999;
        line-height: 1;
        
        &:active {
          color: #333;
        }
      }
    }
    
    .modal-body {
      padding: 32rpx;
      
      .step {
        .step-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 32rpx;
          display: block;
        }
        
        .input-group {
          margin-bottom: 32rpx;
          
          .input-label {
            font-size: 26rpx;
            color: #666;
            margin-bottom: 16rpx;
            display: block;
          }
          
          .phone-input {
            width: 100%;
            height: 88rpx;
            border: 2rpx solid #e0e0e0;
            border-radius: 12rpx;
            padding: 0 24rpx;
            font-size: 28rpx;
            background: #f8f8f8;
            
            &:disabled {
              color: #999;
            }
            
            &:not(:disabled):focus {
              border-color: #3073f6;
            }
          }
          
          .code-input-wrapper {
            display: flex;
            gap: 16rpx;
            
            .code-input {
              flex: 1;
              height: 88rpx;
              border: 2rpx solid #e0e0e0;
              border-radius: 12rpx;
              padding: 0 24rpx;
              font-size: 28rpx;
              
              &:focus {
                border-color: #3073f6;
              }
            }
            
            .send-code-btn {
              min-width: 160rpx;
              height: 88rpx;
              line-height: 88rpx;
              text-align: center;
              background: #3073f6;
              color: #fff;
              border-radius: 12rpx;
              font-size: 24rpx;
              
              &.disabled {
                background: #ccc;
                color: #fff;
              }
              
              &:not(.disabled):active {
                background: #2959d3;
              }
            }
          }
        }
        
        .confirm-btn {
          width: 100%;
          height: 88rpx;
          background: #3073f6;
          color: #fff;
          border: none;
          border-radius: 12rpx;
          font-size: 28rpx;
          font-weight: 600;
          
          &:disabled {
            background: #ccc;
          }
          
          &:not(:disabled):active {
            background: #2959d3;
          }
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .stats-grid {
    grid-template-columns: 1fr 1fr !important;
    gap: 20rpx !important;
  }
  
  .user-goal-card {
    padding: 24rpx !important;
    
    .user-section .user-avatar {
      width: 100rpx !important;
      height: 100rpx !important;
      border-radius: 50rpx !important;
    }
  }
  
  .modify-phone-modal .modify-phone-content {
    width: 90vw !important;
    margin: 0 20rpx;
  }
}
</style>